home *** CD-ROM | disk | FTP | other *** search
/ Danny Amor's Online Library / Danny Amor's Online Library - Volume 1.iso / html / faqs / faq / x-faq / part6 < prev    next >
Encoding:
Text File  |  1995-07-25  |  44.7 KB  |  925 lines

  1. Subject: comp.windows.x Frequently Asked Questions (FAQ) 6/6
  2. Newsgroups: comp.windows.x,news.answers,comp.answers
  3. From: dbl@ics.com (David B. Lewis)
  4. Date: 23 Oct 1994 23:09:14 GMT
  5.  
  6. Archive-name: x-faq/part6
  7. Last-modified: 1994/10/23
  8.  
  9. ----------------------------------------------------------------------
  10. Subject: 132)  Are callbacks guaranteed to be called in the order registered?
  11.  
  12.     Although some books demonstrate that the current implementation of Xt
  13. happens to call callback procedures in the order in which they are registered, 
  14. the specification does not guarantee such a sequence, and supplemental 
  15. authoritative documents (i.e. the Asente/Swick volume) do say that the order is
  16. undefined.  Because the callback list can be manipulated by both the widget and
  17. the application, Xt cannot guarantee the order of execution.
  18.     In general, the callback procedures should be thought of as operating 
  19. independently of one another and should not depend on side-effects of other
  20. callbacks operating; if a seqence is needed, then the single callback to be 
  21. registered can explicitly call other functions necessary.
  22.  
  23. [4/92; thanks to converse@x.org]
  24.  
  25. ----------------------------------------------------------------------
  26. Subject: 133)  Why doesn't XtDestroyWidget() actually destroy the widget?
  27.  
  28.     XtDestroyWidget() operates in two passes, in order to avoid leaving
  29. dangling data structures; the function-call marks the widget, which is not 
  30. actually destroyed until your program returns to its event-loop. 
  31.  
  32. ----------------------------------------------------------------------
  33. Subject: 134)! How do I query the user synchronously using Xt?
  34.     
  35.     It is possible to have code which looks like this trivial callback,
  36. which has a clear flow of control. The calls to AskUser() block until answer
  37. is set to one of the valid values. If it is not a "yes" answer, the code drops
  38. out of the callback and back to an event-processing loop: 
  39.  
  40.     void quit(Widget w, XtPointer client, XtPointer call)
  41.     {
  42.         int             answer;
  43.         answer = AskUser(w, "Really Quit?");
  44.         if (RET_YES == answer)
  45.             {
  46.             answer = AskUser(w, "Are You Really Positive?");
  47.             if (RET_YES == answer)
  48.                 exit(0);
  49.                 }
  50.     }
  51.  
  52.     A more realistic example might ask whether to create a file or whether 
  53. to overwrite it.
  54.     This is accomplished by entering a second event-processing loop and
  55. waiting until the user answers the question; the answer is returned to the
  56. calling function. That function AskUser() looks something like this, where the 
  57. Motif can be replaced with widget-set-specific code to create some sort of 
  58. dialog-box displaying the question string and buttons for "OK", "Cancel" and 
  59. "Help" or equivalents:
  60.  
  61.   int AskUser(w, string)
  62.         Widget          w;
  63.         char           *string;
  64.   {
  65.         int             answer=RET_NONE;    /* some not-used marker */
  66.         Widget          dialog;            /* could cache&carry, but ...*/
  67.         Arg             args[3];
  68.         int             n = 0;
  69.         XtAppContext    context;
  70.  
  71.         n=0;
  72.         XtSetArg(args[n], XmNmessageString, XmStringCreateLtoR(string,
  73.                 XmSTRING_DEFAULT_CHARSET)); n++;
  74.         XtSetArg(args[n], XmNdialogStyle, XmDIALOG_APPLICATION_MODAL); n++;
  75.         dialog = XmCreateQuestionDialog(XtParent(w), string, args, n);
  76.         XtAddCallback(dialog, XmNokCallback, response, &answer);
  77.         XtAddCallback(dialog, XmNcancelCallback, response, &answer);
  78.         XtAddCallback(dialog, XmNhelpCallback, response, &answer);
  79.         XtManageChild(dialog);
  80.  
  81.         context = XtWidgetToApplicationContext(w);
  82.         while ((RET_NONE == answer) || XtAppPending(context)) 
  83.                 XtAppProcessEvent (context, XtIMAll);
  84.         XtDestroyWidget(dialog);  /* blow away the dialog box and shell */
  85.         return answer;
  86.   }
  87.  
  88.     The dialog supports three buttons, which are set to call the same 
  89. function when tickled by the user.  The variable answer is set when the user 
  90. finally selects one of those choices:
  91.  
  92.   void response(w, client, call)
  93.         Widget          w;
  94.         XtPointer client;
  95.         XtPointer call;
  96.   {
  97.         int *answer = (int *) client;
  98.         XmAnyCallbackStruct *reason = (XmAnyCallbackStruct *) call;
  99.         switch (reason->reason) {
  100.         case XmCR_OK:
  101.                 *answer = RET_YES;    /* some #define value */
  102.                 break;
  103.         case XmCR_CANCEL:
  104.                 *answer = RET_NO; 
  105.         break;
  106.         case XmCR_HELP:
  107.                 *answer = RET_HELP;
  108.                 break;
  109.         default:
  110.                 return;
  111.         }
  112. }
  113.  
  114. and the code unwraps back to the point at which an answer was needed and
  115. continues from there.
  116.  
  117. Note that modifications are needed to handle receiving WM_DELETE_WINDOW on
  118. the window; possibly WM_DELETE_WINDOW can be handled by setting the "answer"
  119. variable.
  120.  
  121. [Thanks to Dan Heller (now argv@z-code.com); note that the code in his book
  122. caches the dialog but neglects to make sure that the callbacks point to the
  123. current automatic "answer".]
  124.  
  125. ----------------------------------------------------------------------
  126. Subject: 135)  How do I determine the name of an existing widget?
  127. I have a widget ID and need to know what the name of that widget is.
  128.  
  129.     Users of R4 and later are best off using the XtName() function, which 
  130. will work on both widgets and non-widget objects.
  131.  
  132.     If you are still using R3, you can use this simple bit of code to do 
  133. what you want. Note that it depends on the widget's internal data structures 
  134. and is not necessarily portable to future versions of Xt, including R4.
  135.  
  136.     #include <X11/CoreP.h>
  137.     #include <X11/Xresource.h>
  138.     String XtName (widget)
  139.     Widget widget;    /* WILL work with non-widget objects */
  140.     {
  141.     return XrmNameToString(widget->core.xrm_name);
  142.     }
  143.  
  144. [7/90; modified with suggestion by Larry Rogers (larry@boris.webo.dg.com) 9/91]
  145.  
  146. ----------------------------------------------------------------------
  147. Subject: 136)  Why do I get a BadDrawable error drawing to XtWindow(widget)?
  148. I'm doing this in order to get a window into which I can do Xlib graphics
  149. within my Xt-based program:
  150.  
  151. > canvas = XtCreateManagedWidget ( ...,widgetClass,...) /* drawing area */
  152. > ...
  153. > window = XtWindow(canvas);    /* get the window associated with the widget */
  154. > ...
  155. > XDrawLine (...,window,...);    /* produces error */
  156.  
  157.     The window associated with the widget is created as a part of the 
  158. realization of the widget.  Using a window id of None ("no window") could 
  159. create the error that you describe.  It is necessary to call XtRealizeWidget() 
  160. before attempting to use the window associated with a widget. 
  161.     Note that the window will be created after the XtRealizeWidget() call, 
  162. but that the server may not have actually mapped it yet, so you should also 
  163. wait for an Expose event on the window before drawing into it.
  164.  
  165. ----------------------------------------------------------------------
  166. Subject: 137)  Where can I get documentation on Xaw, the Athena widget set?
  167.  
  168.     Check ftp.x.org in /pub/R5untarred/mit/hardcopy for the originals of
  169. documentation distributed with X11R5. In R6, see xc/doc/specs/Xaw or
  170. xc/doc/hardcopy/Xaw.
  171.  
  172. ----------------------------------------------------------------------
  173. Subject: 138)  What's the difference between actions and callbacks?
  174.  
  175. Actions and callbacks may be closely tied; the user may click a mouse-button
  176. in an object's window, causing an action procedure in that particular object
  177. to be called. As part of its processing of the event, the action procedure
  178. may inform the application via a callback registered on the object. However,
  179. callbacks can be given for any reason, including some that don't arise as a
  180. result of user action; and many actions don't result in any notification to
  181. the application.
  182.  
  183. Callbacks generally are a means of interaction between the user interface
  184. (UI) and some other piece of code interested in the "results"; the interested
  185. party to which the data is communicated is usually the application's back-end
  186. functions but may be another widget in a related part of the UI.  For
  187. example, a text widget invokes a callback to say "the user just entered this
  188. text string; never mind what I had to do to get it or what X events took
  189. place."
  190.  
  191. In object-oriented programming terminology, callback lists are messages
  192. defined by the widget class by which the widget istance notifies another
  193. entity that something significant has happened to the widget.
  194.  
  195. Actions, however, constitute a widget's repertoire of internal i/o
  196. behaviors.  Actions are not about results; actions are about "how", not
  197. "what" gets done. The text widget may define a dozen or two actions which
  198. define how the user can manipulate the text; the procedures for removing a
  199. line of text or switching two words can be associated with particular X event
  200. sequences (and in fact often rely on particular types of events).
  201.  
  202. Actions are (in OOP terminology) methods of the widget class by which the
  203. widget responds to some external stimulus (one or more X events).
  204.  
  205. To avoid confusing yourself on the issue of actions vs. callbacks, try
  206. thinking of actions defined by an application as methods *of the application*
  207. -- applications may define actions, as well -- by which the application
  208. responds to one or more X events (and happens to be handed an object handle
  209. as part of the method argument list). Similarly, callback handlers registered
  210. by an application with a widget can be thought of as methods of the
  211. application which respond to messages from a widget or widgets.
  212.  
  213. [Thanks to Michael Johnson (michael@maine.maine.edu) and to Kerry Kimbrough]
  214.  
  215. ----------------------------------------------------------------------
  216. Subject: 139)  How do I simulate a button press/release event for a widget?
  217.  
  218.     You can do this using XSendEvent(); it's likely that you're not setting
  219. the window field in the event, which Xt needs in order to match to the widget
  220. which should receive the event.
  221.      If you're sending events to your own application, then you can use 
  222. XtDispatchEvent() instead. This is more efficient than XSendEvent() in that you
  223. avoid a round-trip to the server.
  224.     Depending on how well the widget was written, you may be able to call
  225. its action procedures in order to get the effects you want.
  226.  
  227. [courtesy Mark A. Horstman (mh2620@sarek.sbc.com), 11/90]
  228.  
  229. ----------------------------------------------------------------------
  230. Subject: 140)  Can I make Xt or Xlib calls from a signal handler?
  231.  
  232. No. Xlib and Xt have no mutual exclusion for protecting critical sections. If
  233. your signal handler makes such a call at the wrong time (which might be while
  234. the function you are calling is already executing), it can leave the library
  235. in an inconsistent state. Note that the ANSI C standard points out that
  236. behavior of a signal handler is undefined if the signal handler calls any
  237. function other than signal() itself, so this is not a problem specific to
  238. Xlib and Xt; the POSIX specification mentions other functions which may be
  239. called safely but it may not be assumed that these functions are called by
  240. Xlib or Xt functions.
  241.  
  242. Setting a global variable is one of the few permitted operations.  You can
  243. work around the problem by setting a flag in the interrupt handler and later
  244. checking it with a work procedure or a timer event which has previously been
  245. added or by using a custom event loop.
  246.  
  247. R6 Xt has have support for signal handlers; there is a mechanism to set a
  248. flag in a signal handler, and XtAppNextEvent will notice that the flag has
  249. been set and call the associated callbacks.
  250.  
  251. Note: the article in The X Journal 1:4 and the example in the first edition
  252. of O'Reilly & Associates' Volume 6 are in error.
  253.  
  254. [Thanks to Pete Ware (ware@cis.ohio-state.edu) and Donna Converse
  255. (converse@x.org), 5/92]
  256.  
  257. An alternate solution is to create a pipe and add the read side of the pipe
  258. as an input event with XtAppAddInput; then write a byte to the write side of
  259. the pipe with your signal handler (write is re-entrant). The callback for the
  260. read side of the pipe reads the byte and does the actual processing that you
  261. intended. You may want the byte to be the signal number unless your callback
  262. handles only one kind.
  263.  
  264. [Thanks to Steve Kappel (stevek@apertus.com)]
  265.  
  266. ----------------------------------------------------------------------
  267. Subject: 141)  What are these "Xlib sequence lost" errors?
  268.  
  269.     You may see these errors if you issue Xlib requests from an Xlib error 
  270. handler, or, more likely, if you make calls which generate X requests to Xt or 
  271. Xlib from a signal handler, which you shouldn't be doing in any case. 
  272.  
  273. ----------------------------------------------------------------------
  274. Subject: 142)  How can my Xt program handle socket, pipe, or file input?
  275.  
  276.     It's very common to need to write an Xt program that can accept input 
  277. both from a user via the X connection and from some other file descriptor, but 
  278. which operates efficiently and without blocking on either the X connection or 
  279. the other file descriptor.
  280.     A solution is use XtAppAddInput(). After you open your file descriptor,
  281. use XtAppAddInput() to register an input handler. The input handler will be 
  282. called every time there is something on the file descriptor requiring your 
  283. program's attention. Write the input handler like you would any other Xt 
  284. callback, so it does its work quickly and returns.  It is important to use only
  285. non-blocking I/O system calls in your input handlers.
  286.     Most input handlers read the file descriptor, although you can have an 
  287. input handler write or handle exception conditions if you wish.
  288.     Be careful when you register an input handler to read from a disk file.
  289. You will find that the function is called even when there isn't input pending.
  290. XtAppAddInput() is actually working as it is supposed to. The input handler is 
  291. called whenever the file descriptor is READY to be read, not only when there is
  292. new data to be read. A disk file (unlike a pipe or socket) is almost always 
  293. ready to be read, however, if only because you can spin back to the beginning
  294. and read data you've read before.  The result is that your function will almost
  295. always be called every time around XtAppMainLoop(). There is a way to get the 
  296. type of interaction you are expecting; add this line to the beginning of your 
  297. function to test whether there is new data:
  298.          if (ioctl(fd, FIONREAD, &n) == -1 || n == 0) return;
  299. But, because this is called frequently, your application is effectively in a 
  300. busy-wait; you may be better off not using XtAppAddInput() and instead setting 
  301. a timer and in the timer procedure checking the file for input.
  302.  
  303. [courtesy Dan Heller (argv@ora.com), 8/90; mouse@larry.mcrcim.mcgill.edu 5/91;
  304. Ollie Jones (oj@pictel.com) 6/92]
  305.  
  306. There are two alternatives: the simple one is to use XtAppAddTimeout instead
  307. of XtAppAddInput and check for input occasionally; the more complex solution,
  308. and perhaps the better one, is to popen or fork&exec a child which does
  309. blocking reads on the file, relaying what it has read to your application via
  310. a pipe or a socket. XtAppAddInput will work as expected on pipes and
  311. sockets.
  312.  
  313. [Thanks to Kaleb Keithley (kaleb@x.org); 12/93]
  314.  
  315. ----------------------------------------------------------------------
  316. Subject: 143)  What's this R6 error: X Toolkit Error: NULL ArgVal in XtGetValues?
  317.  
  318. The application has a bug! A workaround is described in Section 3.4 of
  319. the R6 release notes.  Here's the relevant excerpt:
  320.  
  321.    GetValuesBC
  322.      Setting this variable to YES allows illegal XtGetValues requests with
  323.      NULL ArgVal to usually succeed, as R5 did.  Some applications erro-
  324.      neously rely on this behavior.  Support for this will be removed in a
  325.      future release.
  326.  
  327. ----------------------------------------------------------------------
  328. Subject: 144)  Why do I get a BadMatch error when calling XGetImage?
  329.  
  330. The BadMatch error can occur if the specified rectangle goes off the edge of 
  331. the screen. If you don't want to catch the error and deal with it, you can take
  332. the following steps to avoid the error:
  333.  
  334. 1) Make a pixmap the same size as the rectangle you want to capture.
  335. 2) Clear the pixmap to background using XFillRectangle.
  336. 3) Use XCopyArea to copy the window to the pixmap.
  337. 4) If you get a NoExpose event, the copy was clean. Use XGetImage to grab the
  338. image from the pixmap.
  339. 5) If you get one or more GraphicsExpose events, the copy wasn't clean, and 
  340. the x/y/width/height members of the GraphicsExpose event structures tell you 
  341. the parts of the pixmap which aren't good.
  342. 6) Get rid of the pixmap; it probably takes a lot of memory.
  343.  
  344. [10/92; thanks to Oliver Jones (oj@pictel.com)]
  345.  
  346. ----------------------------------------------------------------------
  347. Subject: 145)  How can my application tell if it is being run under X?
  348.  
  349.     A number of programs offer X modes but otherwise run in a straight
  350. character-only mode. The easiest way for an application to determine that it is
  351. running on an X display is to attempt to open a connection to the X server:
  352.     
  353.     display = XOpenDisplay(display_name);
  354.     if (display)
  355.         { do X stuff }
  356.     else
  357.         { do curses or something else }
  358. where display_name is either the string specified on the command-line following
  359. -display, by convention, or otherwise is (char*)NULL [in which case 
  360. XOpenDisplay uses the value of $DISPLAY, if set].
  361.  
  362. This is superior to simply checking for the existence a -display command-line 
  363. argument or checking for $DISPLAY set in the environment, neither of which is 
  364. adequate. [5/91]
  365.  
  366. ----------------------------------------------------------------------
  367. Subject: 146)  How do I make a "busy cursor" while my application is computing?
  368. Is it necessary to call XDefineCursor() for every window in my application?
  369.  
  370.     The easiest thing to do is to create a single InputOnly window that
  371. is as large as the largest possible screen; make it a child of your toplevel
  372. window (which must be realized) and it will be clipped to that window, so it
  373. won't affect any other application. (It needs to be as big as the largest
  374. possible screen in case the user enlarges the window while it is busy or
  375. moves elsewhere within a virtual desktop.) Substitute "toplevel" with your
  376. top-most widget here (similar code should work for Xlib-only applications;
  377. just use your top Window):
  378.  
  379.      unsigned long valuemask;
  380.      XSetWindowAttributes attributes;
  381.  
  382.      /* Ignore device events while the busy cursor is displayed. */
  383.      valuemask = CWDontPropagate | CWCursor;
  384.      attributes.do_not_propagate_mask =  (KeyPressMask | KeyReleaseMask |
  385.          ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
  386.      attributes.cursor = XCreateFontCursor(XtDisplay(toplevel), XC_watch);
  387.  
  388.      /* The window will be as big as the display screen, and clipped by
  389.         its own parent window, so we never have to worry about resizing */
  390.      XCreateWindow(XtDisplay(toplevel), XtWindow(toplevel), 0, 0,
  391.          65535, 65535, (unsigned int) 0, 0, InputOnly,
  392.          CopyFromParent, valuemask, &attributes);
  393.  
  394. where the maximum size above could be replaced by the real size of the screen,
  395. particularly to avoid servers which have problems with windows larger than
  396. 32767.
  397.  
  398. When you want to use this busy cursor, map and raise this window; to go back to
  399. normal, unmap it. This will automatically keep you from getting extra mouse
  400. events; depending on precisely how the window manager works, it may or may not
  401. have a similar effect on keystrokes as well.
  402.  
  403. In addition, note also that most of the Xaw widgets support an XtNcursor 
  404. resource which can be temporarily reset, should you merely wish to change the
  405. cursor without blocking pointer events.
  406.  
  407. [thanks to Andrew Wason (aw@cellar.bae.bellcore.com), Dan Heller 
  408. (now argv@z-code.com), and mouse@larry.mcrcim.mcgill.edu; 11/90,5/91]
  409.  
  410. ----------------------------------------------------------------------
  411. Subject: 147)  How do I fork without hanging my parent X program?
  412.  
  413.     An X-based application which spawns off other Unix processes which 
  414. continue to run after it is closed typically does not vanish until all of its 
  415. children are terminated; the children inherit from the parent the open X 
  416. connection to the display. 
  417.     What you need to do is fork; then, immediately, in the child process, 
  418.         close (ConnectionNumber(XtDisplay(widget)));
  419. to close the file-descriptor in the display information. After this do your 
  420. exec. You will then be able to exit the parent.
  421.     Alternatively, before exec'ing make this call, which causes the file 
  422. descriptor to be closed on exec.
  423.         (void) fcntl(ConnectionNumber(XDisplay), F_SETFD, 1);
  424.  
  425. [Thanks to Janet Anstett (anstettj@tramp.Colorado.EDU), Gordon Freedman 
  426. (gjf00@duts.ccc.amdahl.com); 2/91. Greg Holmberg (holmberg@frame.com), 3/93.]
  427.  
  428. ----------------------------------------------------------------------
  429. Subject: 148)  Why doesn't anything appear when I run this simple program?
  430.  
  431. > ...
  432. > the_window = XCreateSimpleWindow(the_display,
  433. >      root_window,size_hints.x,size_hints.y,
  434. >      size_hints.width,size_hints.height,BORDER_WIDTH,
  435. >      BlackPixel(the_display,the_screen),
  436. >      WhitePixel(the_display,the_screen));
  437. > ...
  438. > XSelectInput(the_display,the_window,ExposureMask|ButtonPressMask|
  439. >     ButtonReleaseMask);
  440. > XMapWindow(the_display,the_window);
  441. > ...
  442. > XDrawLine(the_display,the_window,the_GC,5,5,100,100);
  443. > ...
  444.  
  445.     You are right to map the window before drawing into it. However, the 
  446. window is not ready to be drawn into until it actually appears on the screen --
  447. until your application receives an Expose event. Drawing done before that will 
  448. generally not appear. You'll see code like this in many programs; this code 
  449. would appear after the window was created and mapped:
  450.   while (!done)
  451.     {
  452.       XNextEvent(the_display,&the_event);
  453.       switch (the_event.type) {
  454.     case Expose:     /* On expose events, redraw */
  455.         XDrawLine(the_display,the_window,the_GC,5,5,100,100);
  456.         break;
  457.     ...
  458.     }
  459.     }
  460.  
  461.     Note that there is a second problem: some Xlib implementations don't 
  462. set up the default graphics context to have correct foreground/background 
  463. colors, so this program could previously include this code:
  464.   ...
  465.   the_GC_values.foreground=BlackPixel(the_display,the_screen);    /* e.g. */
  466.   the_GC_values.background=WhitePixel(the_display,the_screen);    /* e.g. */
  467.   the_GC = XCreateGC(the_display,the_window,
  468.                 GCForeground|GCBackground,&the_GC_values);
  469.   ...
  470.  
  471. Note: the code uses BlackPixel and WhitePixel to avoid assuming that 1 is 
  472. black and 0 is white or vice-versa.  The relationship between pixels 0 and 1 
  473. and the colors black and white is implementation-dependent.  They may be 
  474. reversed, or they may not even correspond to black and white at all.
  475.  
  476. Also note that actually using BlackPixel and WhitePixel is usually the wrong 
  477. thing to do in a finished program, as it ignores the user's preference for 
  478. foreground and background.
  479.  
  480. And also note that you can run into the same situation in an Xt-based program
  481. if you draw into the XtWindow(w) right after it has been realized; it may
  482. not yet have appeared.
  483.  
  484. ----------------------------------------------------------------------
  485. Subject: 149)  What is the difference between a Screen and a screen?
  486.  
  487.     The 'Screen' is an Xlib structure which includes the information about
  488. one of the monitors or virtual monitors which a single X display supports. A 
  489. server can support several independent screens. They are numbered unix:0.0,
  490. unix:0.1, unix:0.2, etc; the 'screen' or 'screen_number' is the second digit --
  491. the 0, 1, 2 which can be thought of as an index into the array of available 
  492. Screens on this particular Display connection.
  493.     The macros which you can use to obtain information about the particular
  494. Screen on which your application is running typically have two forms -- one
  495. which takes a Screen and one with takes both the Display and the screen_number.
  496.     In Xt-based programs, you typically use XtScreen(widget) to determine 
  497. the Screen on which your application is running, if it uses a single screen.
  498.     (Part of the confusion may arise from the fact that some of the macros
  499. which return characteristics of the Screen have "Display" in the names -- 
  500. XDisplayWidth, XDisplayHeight, etc.)
  501.     
  502. ----------------------------------------------------------------------
  503. Subject: 150)  Can XGetWindowAttributes get a window's background pixel/pixmap?
  504.  
  505.     No.  Once set, the background pixel or pixmap of a window cannot be 
  506. re-read by clients.  The reason for this is that a client can create a pixmap,
  507. set it to be the background pixmap of a window, and then free the pixmap. The 
  508. window keeps this background, but the pixmap itself is destroyed.  If you're 
  509. sure a window has a background pixel (not a pixmap), you can use XClearArea() 
  510. to clear a region to the background color and then use XGetImage() to read 
  511. back that pixel.  However, this action alters the contents of the window, and 
  512. it suffers from race conditions with exposures. [courtesy Dave Lemke of NCD 
  513. and Stuart Marks of Sun]
  514.  
  515.     Note that the same applies to the border pixel/pixmap. This is a 
  516. (mis)feature of the protocol which allows the server is free to manipulate the
  517. pixel/pixmap however it wants.  By not requiring the server to keep the 
  518. original pixel or pixmap, some (potentially a lot of) space can be saved. 
  519. [courtesy Jim Fulton, then of X Consortium]
  520.  
  521. ----------------------------------------------------------------------
  522. Subject: 151)  How do I create a transparent window?
  523.     
  524.     A completely transparent window is easy to get -- use an InputOnly
  525. window. In order to create a window which is *mostly* transparent, you have
  526. several choices:
  527.     - the SHAPE extension first released with X11R4 offers an easy way to
  528. make non-rectangular windows, so you can set the shape of the window to fit the
  529. areas where the window should be nontransparent; however, not all servers 
  530. support the extension.
  531.     - a machine-specific method of implementing transparent windows for
  532. particular servers is to use an overlay plane supported by the hardware.  Note 
  533. that there is no X notion of a "transparent color index".
  534.     - a generally portable solution is to use a large number of tiny 
  535. windows, but this makes operating on the application as a unit difficult.
  536.     - a final answer is to consider whether you really need a transparent
  537. window or if you would be satisfied with being able to overlay your application
  538. window with information; if so, you can draw into separate bitplanes in colors
  539. that will appear properly.
  540.  
  541. [thanks to der Mouse, mouse@lightning.McRCIM.McGill.EDU, 3/92; see also
  542. The X Journal 1:4 for a more complete answer, including code samples for this
  543. last option]
  544.  
  545. ----------------------------------------------------------------------
  546. Subject: 152)  Why doesn't GXxor produce mathematically-correct color values?
  547.  
  548.     When using GXxor you may expect that drawing with a value of black on a
  549. background of black, for example, should produce white. However, the drawing
  550. operation does not work on RGB values but on colormap indices. The color that
  551. the resulting colormap index actually points to is undefined and visually
  552. random unless you have actually filled it in yourself. [On many X servers Black
  553. and White often 0/1 or 1/0; programs taking advantage of this mathematical
  554. coincidence will break.]
  555.     If you want to be combining colors with GXxor, then you should be 
  556. allocating a number of your own color cells and filling them with your chosen
  557. pre-computed values.
  558.     If you want to use GXxor simply to switch between two colors, then you 
  559. can take the shortcut of setting the background color in the GC (graphics 
  560. context) to 0 and the foreground color to a value such that when it draws over 
  561. red, say, the result is blue, and when it draws over blue the result is red. 
  562. This foreground value is itself the XOR of the colormap indices of red and 
  563. blue.
  564.  
  565. [Thanks to Chris Flatters (cflatter@zia.aoc.nrao.EDU) and Ken Whaley 
  566. (whaley@spectre.pa.dec.com), 2/91]
  567.  
  568. ----------------------------------------------------------------------
  569. Subject: 153)  Why does every color I allocate show up as black?
  570.  
  571.     Make sure you're using 16 bits and not 8.  The red, green, and blue 
  572. fields of an XColor structure are scaled so that 0 is nothing and 65535 is 
  573. full-blast. If you forget to scale (using, for example, 0-255 for each color) 
  574. the XAllocColor function will perform correctly but the resulting color is 
  575. usually black. 
  576.  
  577. [Thanks to Paul Asente, asente@adobe.com, 7/91]
  578.  
  579. ----------------------------------------------------------------------
  580. Subject: 154)  Why do I get a protocol error when creating a cursor (sic)?
  581.  
  582.     You may have had this code working on a monochrome system by
  583. coincidence.  Cursor pixmaps must always have a depth of 1; when you create
  584. the cursor pixmap use the depth of 1 rather than the default depth of the
  585. screen.
  586.  
  587. ----------------------------------------------------------------------
  588. Subject: 155)  Why can't my program get a standard colormap?
  589. I have an image-processing program which uses XGetRGBColormap() to get the 
  590. standard colormap, but it doesn't work. 
  591.  
  592.     XGetRGBColormap() when used with the property XA_RGB_DEFAULT_MAP does 
  593. not create a standard colormap -- it just returns one if one already exists.
  594. Use xstdcmap or do what it does in order to create the standard colormap first.
  595.  
  596. [1/91; from der Mouse (mouse@larry.mcrcim.mcgill.edu)]
  597.  
  598. ----------------------------------------------------------------------
  599. Subject: 156)  Why does the pixmap I copy to the screen show up as garbage? 
  600.  
  601.     The initial contents of pixmaps are undefined.  This means that most
  602. servers will allocate the memory and leave around whatever happens to be there 
  603. -- which is usually garbage.  You probably want to clear the pixmap first using
  604. XFillRectangle() with a function of GXcopy and a foreground pixel of whatever 
  605. color you want as your background (or 0L if you are using the pixmap as a 
  606. mask). [courtesy Dave Lemke of NCD and Stuart Marks of Sun]
  607.  
  608. ----------------------------------------------------------------------
  609. Subject: 157)  How can I most quickly send an image to the X server? 
  610.  
  611.     The fastest mechanism may be to use an XImage and the shared-memory
  612. extension to reduce the transmission time.
  613.     The MIT-SHM code, documentation, and example client programs can be 
  614. found on the X11R5 source tape; many vendors also support the extension.
  615.     If bandwidth is a problem, the X Image Extension has facilities for
  616. transmitting compressed images.
  617.  
  618. ----------------------------------------------------------------------
  619. Subject: 158)  How do I check whether a window ID is valid?
  620. My program has the ID of a window on a remote display. I want to check whether
  621. the window exists before doing anything with it.
  622.  
  623.     Because X is asynchronous, there isn't a guarantee that the window 
  624. would still exist between the time that you got the ID and the time you sent an
  625. event to the window or otherwise manipulated it. What you should do is send the
  626. event without checking, but install an error handler to catch any BadWindow
  627. errors, which would indicate that the window no longer exists. This scheme
  628. will work except on the [rare] occasion that the original window has been
  629. destroyed and its ID reallocated to another window. 
  630.     You can use this scheme to make a function which checks the validity
  631. of a window; you can make this operation almost synchronous by calling
  632. XSync() after the request, although there is still no guarantee that the
  633. window will exist after the result (unless the sterver is grabbed). On the 
  634. whole, catching the error rather than pre-checking is preferable.
  635.  
  636. [courtesy Ken Lee (now kenton@esd.sgi.com), 4/90; 12/93]
  637.  
  638. ----------------------------------------------------------------------
  639. Subject: 159)  Can I have two applications draw to the same window?
  640.  
  641.     Yes. The X server assigns IDs to windows and other resources (actually,
  642. the server assigns some bits, the client others), and any application that 
  643. knows the ID can manipulate the resource [almost any X server resource, except
  644. for GCs and private color cells, can be shared].
  645.     The problem you face is how to disseminate the window ID to multiple 
  646. applications. A simple way to handle this (and which solves the problem of the
  647. applications' running on different machines) is in the first application to 
  648. create a specially-named property on the root-window and put the window ID into
  649. it. The second application then retrieves the property, whose name it also
  650. knows, and then can draw whatever it wants into the window.
  651.     [Note: this scheme works iff there is only one instance of the first
  652. application running, and the scheme is subject to the limitations mentioned
  653. in the Question about using window IDs on remote displays.]
  654.     Note also that you will still need to coordinate any higher-level 
  655. cooperation among your applications; you may find the Synchronization
  656. extension in R6 useful for this.
  657.     Note also that two processes can share a window but should not try to 
  658. use the same server connection. If one process is a child of the other, it 
  659. should close down the connection to the server and open its own connection.
  660.     Note also that Display IDs and GC values describe addresses local
  661. to an application and cannot be transmitted to another application; note also
  662. that if you are using Xt you may not share widget IDs, which are local to the
  663. client.
  664.     Note also that several clients may draw to a window but for particular
  665. X events such as button-presses only one client can receive the event.
  666.  
  667. [mostly courtesy Phil Karlton (karlton@wpd.sgi.com) 6/90]
  668.  
  669. ----------------------------------------------------------------------
  670. Subject: 160)  Why can't my program work with tvtwm or swm?
  671.  
  672.     A number of applications, including xwd, xwininfo, and xsetroot, do not
  673. handle the virtual root window which tvtwm and swm use; they typically return 
  674. the wrong child of root. A general solution is to add this code or to use it in
  675. your own application where you would normally use RootWindow(dpy,screen):
  676.  
  677. /* Function Name: GetVRoot
  678.  * Description: Gets the root window, even if it's a virtual root
  679.  * Arguments: the display and the screen
  680.  * Returns: the root window for the client
  681.  */
  682. #include <X11/Xatom.h>
  683. Window GetVRoot(dpy, scr)
  684. Display        *dpy;
  685. int             scr;
  686. {
  687. Window          rootReturn, parentReturn, *children;
  688. unsigned int    numChildren;
  689. Window          root = RootWindow(dpy, scr);
  690. Atom            __SWM_VROOT = None;
  691. int             i;
  692.  
  693.   __SWM_VROOT = XInternAtom(dpy, "__SWM_VROOT", False);
  694.   XQueryTree(dpy, root, &rootReturn, &parentReturn, &children, &numChildren);
  695.   for (i = 0; i < numChildren; i++) {
  696.     Atom            actual_type;
  697.     int             actual_format;
  698.     long            nitems, bytesafter;
  699.     Window         *newRoot = NULL;
  700.  
  701.     if (XGetWindowProperty(dpy, children[i], __SWM_VROOT, 0, 1,
  702.         False, XA_WINDOW, &actual_type, &actual_format, &nitems,
  703.             &bytesafter, (unsigned char **) &newRoot) == Success && newRoot) {
  704.             root = *newRoot;
  705.             break;
  706.         }
  707.     }
  708.  
  709.     XFree((char *)children);
  710.     return root;
  711. }
  712.  
  713. [courtesy David Elliott (dce@smsc.sony.com). Similar code is in ssetroot, a
  714. version of xsetroot distributed with tvtwm. 2/91]
  715.  
  716. A header file by Andreas Stolcke of ICSI on ftp.x.org:contrib/vroot.h 
  717. functions similarly by providing macros for RootWindow and DefaultRootWindow;
  718. code can include this header file first to run properly in the presence of a
  719. virtual desktop.
  720.  
  721. (Note the possible race condition.)
  722.     
  723. ----------------------------------------------------------------------
  724. Subject: 161)  Can I rely on a server which offers backing store?  
  725.  
  726.     You can assume only that the X server has the capability of doing
  727. backing store and that it might do so and keep your application's visuals
  728. up-to-date without your program's involvement; however, the X server can run
  729. out of resources at any time, so you must be able to handle the exposure
  730. events yourself. You cannot rely on a server which offers backing store to
  731. maintain your windows' contents on your behalf.
  732.  
  733. ----------------------------------------------------------------------
  734. Subject: 162)  How do I catch the "close window" event to avoid "fatal IO error"?
  735.  
  736.     Several windows managers offer a function such as f.kill or f.delete
  737. which sends a message to the application that it should delete its window;
  738. this is usually interpreted as a shutdown message.
  739.     The application needs to catch the WM_DELETE_WINDOW client message.
  740. There is a good example in the xcalc sources in X11R5.
  741.     Motif-based applications should in addition set the resource
  742. XmNdeleteResponse on the top-level shell to XmDO_NOTHING, whether they are
  743. using the Motif window manager or not.
  744.     If the application doesn't handle this message the window manager may
  745. wind up calling XKillClient, which disconnects the client from the display and
  746. typically gives an Xlib error along the lines of "fatal IO error 32 (Broken 
  747. pipe)".
  748.  
  749. [Thanks to Kaleb Keithley, kaleb@x.org; 11/93]
  750.  
  751. ----------------------------------------------------------------------
  752. Subject: 163)  How do I keep a window from being resized by the user?
  753.  
  754.     Resizing the window is done through the window manager; window managers
  755. can pay attention to the size hints your application places on the window, but 
  756. there is no guarantee that the window manager will listen. You can try setting 
  757. the minimum and maximum size hints to your target size and hope for the best. 
  758.     Note that you may wish to reconsider your justification for this
  759. restriction.
  760.  
  761. ----------------------------------------------------------------------
  762. Subject: 164)  How do I keep a window in the foreground at all times?
  763.  
  764.     It's rather antisocial for an application to constantly raise itself
  765. [e.g. by tracking VisibilityNotify events] so that it isn't overlapped -- 
  766. imagine the conflict between two such programs running.  
  767.     The only sure way to have your window appear on the top of the stack
  768. is to make the window override-redirect; this means that you are temporarily
  769. assuming window-management duties while the window is up, so you want to do 
  770. this infrequently and then only for short periods of time (e.g. for popup 
  771. menus or other short parameter-setting windows).
  772.  
  773. [thanks to der Mouse (mouse@larry.mcrcim.mcgill.edu); 7/92]
  774.  
  775. ----------------------------------------------------------------------
  776. Subject: 165)  How do I make text and bitmaps blink in X?
  777.  
  778.     There is no easy way.  Unless you're willing to depend on some sort of
  779. extension (as yet non-existent), you have to arrange for the blinking yourself,
  780. either by redrawing the contents periodically or, if possible, by playing games
  781. with the colormap and changing the color of the contents.
  782.  
  783. [Thanks to mouse@larry.mcrcim.mcgill.edu (der Mouse), 7/91]
  784.  
  785. ----------------------------------------------------------------------
  786. Subject: 166)  How do I get a double-click in Xlib?
  787.  
  788.     Users of Xt have the support of the translation manager to help 
  789. get notification of double-clicking.
  790.     There is no good way to get only a double-click in Xlib, because the 
  791. protocol does not provide enough support to do double-clicks.  You have to do 
  792. client-side timeouts, unless the single-click action is such that you can defer
  793. actually taking it until you next see an event from the server.  Thus, you 
  794. have to do timeouts, which means system-dependent code.  On most UNIXish 
  795. implementations, you can use XConnectionNumber to get the file descriptor of 
  796. the X connection and then use select() or something similar on that.
  797.     Note that many user-interface references suggest that a double-click
  798. be used to extend the action indicated by a single-click; if this is the case
  799. in your interface then you can execute the first action and as a compromise
  800. check the timestamp on the second event to determine whether it, too, should
  801. be the single-click action or the double-click action.
  802.  
  803. [Thanks to mouse@larry.mcrcim.mcgill.edu (der Mouse), 4/93]
  804.  
  805. ----------------------------------------------------------------------
  806. Subject: 167)  How do I render rotated text?
  807.     
  808.     The X Logical Font Description was enhanced for R6 to allow embedding
  809. a transformation matrix in certain fields of an XLFD name.  Thus arbitrary
  810. rotation, scaling, shearing, etc. are possible.  To draw text along an
  811. arbitrarily sloped line, open a font with the appropriate rotation
  812. transformation and individually place and draw each character.  Drawing text
  813. along a curve requires a different font for each character orientation
  814. needed.  The overhead of opening so many fonts is somewhat mitigated by
  815. another XLFD extension which allows you to ask for a subset of the
  816. characters.  See section 4 of xc/doc/specs/XLFD/xlfd.tbl.ms in the R6
  817. distribution.  Also see The X Resource, Issue Nine, p. 211, "New Font
  818. Technology for X11R6," Nathan Meyers.  (Note: due to changes after
  819. publication deadline, the information in the Meyers paper about the syntax of
  820. character set subsetting is out of date.) These capabilities are also
  821. available to an R5 X server using an R6 font server.
  822.  
  823.     If you are not using R6, your only choice, if you want to stay within
  824. the core X protocol, is to render the text into a pixmap, read it back via
  825. XGetImage(), rotate it "by hand" with whatever matrices you want, and put it
  826. back to the server via XPutImage(); more specifically:
  827.  
  828.     Your only choice, if you want to stay within the core X protocol, is to
  829. render the text into a pixmap, read it back via XGetImage(), rotate it "by 
  830. hand" with whatever matrices you want, and put it back to the server via 
  831. XPutImage(); more specifically:
  832.     1) create a bitmap B and write your text to it.
  833.     2) create an XYBitmap image I from B (via XGetImage).
  834.     3) create an XYBitmap Image I2 big enough to handle the transformation.
  835.     4) for each x,y in I2, I2(x,y) = I(a,b) where 
  836.         a = x * cos(theta) - y * sin(theta)
  837.         b = x * sin(theta) + y * cos(theta)
  838.     5) render I2
  839.     Note that you should be careful how you implement this not to lose
  840. bits; an algorithm based on shear transformations may in fact be better.
  841.     The high-level server-extensions and graphics packages available for X 
  842. also permit rendering of rotated text: Display PostScript, PEX, PHiGS, and GKS,
  843. although most are not capable of arbitrary rotation and probably do not use the
  844. same fonts that would be found on a printer.
  845.     In addition, if you have enough access to the server to install a font
  846. on it, you can create a font which consists of letters rotated at some
  847. predefined angle. Your application can then itself figure out placement of each
  848. glyph.
  849.  
  850. [courtesy der Mouse (mouse@larry.mcrcim.mcgill.edu), Eric Taylor
  851. (etaylor@wilkins.bmc.tmc.edu), and Ken Lee (now kenton@esd.sgi.com), 11/90;
  852. Liam Quin (lee@sq.com), 12/90; Dave Wiggins (dpw@x.org), 5/94.]
  853.  
  854. InterViews (C++ UI toolkit, in the X contrib software) has support for
  855. rendering rotated fonts in X.  It could be one source of example code.
  856. [Brian R. Smith (brsmith@cs.umn.edu), 3/91]
  857.  
  858. Another possibility is to use the Hershey Fonts; they are stroke-rendered and
  859. can be used by X by converting them into XDrawLine requests.
  860. [eric@pencom.com, 10/91]
  861.  
  862. The xrotfont program by Alan Richardson (mppa3@syma.sussex.ac.uk) (posted to
  863. comp.sources.x July 14 1992) paints a rotated font by implementing the method
  864. above and by using an outline (Hershey) font.
  865.  
  866. The xvertext package by Alan Richardson (mppa3@syma.sussex.ac.uk) is a set of
  867. functions to facilitate the writing of text at any angle.  It is on ftp.x.org
  868. as contrib/xvertext.5.0.shar.Z.
  869.  
  870. O'Reilly's X Resource issue 3 includes information from HP about
  871. modifications to the X fonts server which provide for rotated and scaled
  872. text.  The modifications are on ftp.x.org in contrib/hp_xlfd_enhancements.
  873.  
  874. Bristol Technology's XPrinter product has extensions to Xlib to rotate text.
  875. Send email to info@bristol.com for more details.
  876.  
  877. ----------------------------------------------------------------------
  878. Subject: 168)  Why doesn't my multi-threaded X program work (sic) ? 
  879.   
  880. Support in Xlib and Xt for multi-threaded X programs is included in X11R6.
  881. See the documentation for XInitThreads, XtToolkitThreadInitialize, section
  882. 2.7 of the Xlib specification, section 7.12 of the Xt specification, and the
  883. article "Multi-Threaded Xlib," The X Resource, Issue 5, by Stephen Gildea.
  884. The following discussion applies only to pre-R6 libraries:
  885.  
  886. You cannot use non-thread aware, non-reentrant libraries with threads.
  887.  
  888. If you must do this, you have only one choice: call the functions from the
  889. initial thread only.
  890.  
  891. Why opening windows from other threads causes protocol errors can be
  892. explained easily: you are accessing shared resources (the display
  893. structure, the connection to the display, static data in the Xlib) from
  894. a number of threads at the same time, without using any form of
  895. exclusive access control.
  896.  
  897. [Thanks to casper@fwi.uva.nl (Casper H.S. Dik)]
  898.  
  899. ----------------------------------------------------------------------
  900. Subject: 169)  What is the X Registry? (How do I reserve names?)
  901.  
  902.     There are places in the X Toolkit, in applications, and in the X
  903. protocol that define and use string names. The context is such that conflicts
  904. are possible if different components use the same name for different things.
  905.     The X Consortium maintains a registry of names in these domains:
  906. orgainization names, selection names, selection targets, resource types,
  907. application classes, and class extension record types; and several others.
  908.     The list as of April 1994 is in the file xc/registry in the R6
  909. distribution. The current Registry is also available by sending "send docs
  910. registry" to the xstuff mail server.
  911.     To register names (first come, first served) or to ask questions send 
  912. to xregistry@x.org; be sure to include a postal address for confirmation.
  913.  
  914. [11/90; condensed from Asente/Swick Appendix H; 1/94]
  915. ----------------------------------------------------------------------
  916.  
  917. David B. Lewis                     faq%craft@uunet.uu.net
  918.  
  919.         "Just the FAQs, ma'am." -- Joe Friday 
  920.  
  921. -- 
  922. David B. Lewis            Temporarily at but not speaking for ICS
  923. day: dbl@ics.com        evening: dbl%craft@uunet.uu.net
  924.  
  925.